import 'package:flutter/widgets.dart';
import 'package:flutter_module/util/log.dart';

class ActivityLifecycleWatcher extends StatefulWidget {
  static const String routeName = "/LifecycleWatcher";

  @override
  _ActivityLifecycleWatcherState createState() => _ActivityLifecycleWatcherState();
}

class _ActivityLifecycleWatcherState extends State<ActivityLifecycleWatcher> with WidgetsBindingObserver {
  AppLifecycleState? _lastLifecycleState;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      _lastLifecycleState = state;
      logger.print("状态改变：$state");
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_lastLifecycleState == null)
      return Text('This widget has not observed any lifecycle changes.', textDirection: TextDirection.ltr);

    return Text('The most recent lifecycle state this widget observed was: $_lastLifecycleState.',
        textDirection: TextDirection.ltr);
  }
}

void main() {
  runApp(Center(child: ActivityLifecycleWatcher()));
}
